/*补充关联信息*/
import React, { Component } from 'react';
import { Text, View, Image, TouchableOpacity, ScrollView, Alert } from "react-native";
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { AddLongBtn } from './_components/AddLongBtn.js';
import { TitleView } from './_components/TitleView.js';
import { Common } from '../../../component/common/Common.js'
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import OrderCreactService from './_common/service';
import OrderAPIService from './_common/OrderAPIService';
import { orderBlockStyle } from './_common/style';
import ToastUtil from '../../../utils/toast';
const scale = GLOBAL.SCALE
let addBtn = require('../../../imgs/apply/orderAddBtn.png');

export class OrderOtherInfoPage extends Component {
	static navigationOptions = {
		header: null
	}
	requesting;
	constructor(props) {
		super(props);
		this.jumpPage = OrderCreactService.jump.bind(this);
		this.resetPage = OrderCreactService.reset.bind(this);
		let { tCode, orderId, orderType, productList, totalFeeAmt, companyId } = props.navigation.state.params;
		this.state = {
			intentionData: [],
			associateList: [],
			status: 'data',
			orderId: orderId,
			orderType: orderType,
			tCode: tCode,
			isAssociated: false,
			productList,
			totalFeeAmt,
			companyId,
		}
		this.isUnite = false;
	}

	componentWillMount () {
		this.getOrderBaseInfo();
		this.state.orderType === 'P' && this.state.tCode !== 'E' ? this.getIntentionList() : this.setState({ intentionData: false });
		this.getAssociateTypeList();
	}

	async getOrderBaseInfo () {
		let orderInfo = await OrderAPIService.getOrderDetail({ orderId: this.state.orderId, queryType: 'ORDER_ALL_INFO' });
		this.isUnite = orderInfo.isUnite;
	}

	//客户意向 -数据
	async getIntentionList () {
		let responseData = await OrderAPIService.getIntentionList({ orderId: this.state.orderId }) || [];
		if (responseData) {
			this.setState({
				intentionData: responseData
			})
		}
	}

	//客户意向  -跳转
	goIntentionPage = (item) => {
		let params = {
			orderId: this.state.orderId,
			type: 'OrderOtherInfoPage',
			intentionItem: item || '',
			intentionList: this.state.intentionData,
			productList: this.state.productList,
			totalFeeAmt: this.state.totalFeeAmt,
			companyId: this.state.companyId
		}
		this.jumpPage('IntentionAddPage', params, this.getIntentionList.bind(this));
	}

	//客户意向  -删除
	async removeIntentionItem (extId) {
		let respData = await OrderAPIService.intentionDel({ extId }) || [];

		if (respData) {
			ToastUtil.showWarning('意向删除成功');
			this.getIntentionList();
		}
	}

	removeConfirm (extId) {
		Alert.alert('提示', '确定要删除该意向客户吗？', [
			{
				text: '取消',
			}, {
				text: '确定',
				onPress: () => {
					this.removeIntentionItem(extId)
				}
			}
		])
	}

	//关联信息  -数据
	async getAssociateTypeList () {
		let responseData = await OrderAPIService.getMapedList({ queryType: 'ORDER_MAPPING_LIST', orderId: this.state.orderId }) || [];
		responseData.map(item => {
			item.mappingQ = 0;
			if (item.orderMappingList.length > 0) {
				this.setState({ isAssociated: true });
			}
			item.orderMappingList.map(oM => {
				item.mappingQ += Number.parseFloat(oM.quantity);
			})
		})
		this.setState({ associateList: responseData });
	}

	//关联信息  -跳转
	goReportPage = () => {
		let params = {
			orderId: this.state.orderId,
			orderType: this.state.orderType,
		}
		this.jumpPage('ReportAssociatePage', params, this.getAssociateTypeList.bind(this));
	}

	//提交或保存
	async	nextStep (str, opType) {
		if (this.requesting) return;
		let { intentionData, isAssociated, orderType, tCode } = this.state;
		//采购 自营 提交 验证
		if (orderType === 'P' && this.state.tCode !== "E" && opType == 'submit' && intentionData.length < 1 && !isAssociated && !this.isUnite) {
			ToastUtil.showWarning('关联和意向必须填写一项');
			return;
		}

		let sendData = {
			submitStep: str,
			orderInfo: {
				orderId: this.state.orderId
			}
		}
		this.setState({
			status: 'loading'
		})
		this.requesting = true;
		let saveData = await OrderAPIService.orderAdd(sendData)
		this.setState({
			status: 'data'
		})

		if (saveData) {
			setTimeout(() => {
				this.requesting = false;
			}, 1000)
			let msg = '已保存到草稿';
			// status 0,1,2,3 已通过 审批中 已驳回 草稿


			let status = 0;
			if (tCode == 'E' && opType == 'submit') {
				//RPT_AUDITING : 审批 , RPT_AUDIT_PASS : 进行中':
				status = saveData.status == 'RPT_AUDITING' ? '1' : '2';
			} else {
				status = opType == 'submit' ? 1 : 0;
			}


			//let status = 'RPT_DRAFT';
			if (opType == 'submit') {
				msg = '提交成功';
				//status = submitType ? 1 : 0;
			};
			// if (saveData.status) {
			// 	status = saveData.status
			// }



			ToastUtil.showSuccess(msg).then(() => {

				console.log('99999999-orderType', orderType, 'tCode', tCode, 'status', status)
				if (tCode == 'C' || tCode == 'A') {
					this.resetPage(orderType, tCode, 1)
				} else if (tCode == 'QH') {
					this.resetPage(orderType, tCode, 2)
				} else {
					this.resetPage(orderType, tCode, status)
				}


				//this.resetPage(orderType, tCode, status)
			})
		} else {
			this.requesting = false;
		}
	}
	//顶部关闭按钮
	_headCloes = () => {
		this.props.navigation.goBack()
	}
	render () {
		let { status, intentionData, isAssociated, orderType, associateList } = this.state;
		let associateName = '关联' + (orderType === 'P' ? '销售成交' : '采购成交');
		return (
			<View style={orderBlockStyle.container}>
				<ScrollView showsVerticalScrollIndicator={false}>
					<Common type="headCloes" callBack={this._headCloes} />
					<TitleView title={'其他'} describe={'选择性填写'} />
					<View style={{ marginTop: 30 * scale }}>
						{intentionData && intentionData.length <= 0 ? (
							<TouchableOpacity style={orderBlockStyle.inputBox} onPress={this.goIntentionPage}>
								<Image style={orderBlockStyle.inputKk} source={require('../../../imgs/apply/inputText.png')} />
								<View style={orderBlockStyle.inputNr}>
									<Text>填写意向客户</Text>
									<Image style={{ width: 6 * scale, height: 11 * scale }} source={require('../../../imgs/arrow-left.png')} />
								</View>
							</TouchableOpacity>
						) : (
								intentionData && intentionData.map((item, index) => {
									let { companyName, goodsName, planSellQuantity, planRecvStyle, planRecvType, planSalesAddress, planSellBeginDate, planSellEndDate, planSalesAmt, planSellPrice, planRecvStyleName, planRecvTypeName, companyAddressName, planSalesAddressName, planRemark, planFinanceCost, planGrossProfit, planLogisticsCost } = item;
									return (
										<TouchableOpacity style={[orderBlockStyle.infoBox]} onPress={() => {
											this.goIntentionPage(item)
										}} key={index}>
											<Image style={orderBlockStyle.infoImg} source={require('../../../imgs/apply/infoImg.png')} />
											<View style={orderBlockStyle.infoHead} >
												<Text style={orderBlockStyle.infoTitle}>填写意向客户</Text>
												<Image style={{ width: 6 * scale, height: 11 * scale }} source={require('../../../imgs/arrow-left.png')} />
											</View>
											<View style={orderBlockStyle.infoBody}>
												<Text style={orderBlockStyle.infoText} numberOfLines={2}>
													{companyName ? '客户：' + companyName + '，' : ''}
													{goodsName ? '商品：' + goodsName + '，' : ''}
													{planSellQuantity ? '数量：' + planSellQuantity + '吨，' : ''}
													{planSellPrice ? '单价：' + planSellPrice + '元，' : ''}
													{(planSellBeginDate && planSellEndDate ? '时间：' + planSellBeginDate + '至' + planSellEndDate : '')}
													{planRecvTypeName ? '付款类型 ：' + planRecvTypeName : ''}
													{companyAddressName ? '客户收货地址：' + companyAddressName : ''}
													{planLogisticsCost ? '物流费用：' + planLogisticsCost + '元，' : ''}
													{planFinanceCost ? '财务费用：' + planFinanceCost + '元，' : ''}
													{planRemark ? '简要分析：' + planRemark : ''}
												</Text>
												<View style={[orderBlockStyle.removeItem, { flexDirection: 'row-reverse' }]}>
													<Text onPress={() => { this.removeConfirm(item.extId) }} style={orderBlockStyle.removeBtn}>删除</Text>
												</View>
											</View>
										</TouchableOpacity>
									)
								})
							)}

						{
							intentionData && intentionData.length > 0 ? (
								<TouchableOpacity style={[orderBlockStyle.infoAddBox, { marginBottom: 15 * scale, }]} onPress={this.goIntentionPage}>
									<Image source={addBtn} />
									<Text style={orderBlockStyle.infoAddText}>新增</Text>
								</TouchableOpacity>
							) : null
						}

						{!isAssociated ? (
							<TouchableOpacity style={orderBlockStyle.inputBox} onPress={this.goReportPage}>
								<Image style={orderBlockStyle.inputKk} source={require('../../../imgs/apply/inputText.png')} />
								<View style={orderBlockStyle.inputNr}>
									<Text>{associateName}</Text>
									<Image style={{ width: 6 * scale, height: 11 * scale }} source={require('../../../imgs/arrow-left.png')} />
								</View>
							</TouchableOpacity>
						) : (
								<TouchableOpacity style={[orderBlockStyle.infoBox]} onPress={this.goReportPage}>
									<Image style={orderBlockStyle.infoImg} source={require('../../../imgs/apply/infoImg.png')} />
									<View style={orderBlockStyle.infoHead}>
										<Text style={orderBlockStyle.infoTitle}>{associateName}</Text>
										<Image style={{ width: 6 * scale, height: 11 * scale }} source={require('../../../imgs/arrow-left.png')} />
									</View>
									<View style={orderBlockStyle.infoBody}>
										{associateList && associateList.map((item, index) => {
											return <Text key={index}>{item.goodsName}，已关联：{item.mappingQ + item.uomName}</Text>
										})}
									</View>
								</TouchableOpacity>
							)}
					</View>
					{/* {orderType == 'P' ? <Text style={{
						fontSize: 12 * scale,
						marginTop: 20 * scale,
						color: '#F66464'
					}}>只需要填写一项即可，如两个都填写，默认关联生效</Text> : null} */}
				</ScrollView>
				<AddLongBtn direction="left" callBack={this._headCloes} text="上一步" bottom="20" colorBg={style.color.ceruleanUp} />
				<TouchableOpacity onPress={() => { this.nextStep('SAVE_ORDER_DRAFT', 'save') }} style={orderBlockStyle.saveBtnBox}>
					<Text style={orderBlockStyle.saveBtn}>保存</Text>
				</TouchableOpacity>
				<AddLongBtn callBack={() => { this.nextStep('ORDER_SUBMIT_AUDIT', 'submit') }} text="提交" direction="right" bottom="20" colorBg={style.color.cerulean} />
				{
					status != 'data' ? (<View style={orderBlockStyle.statusStyle}><PageStatusIndex status={status} /></View>) : null
				}
			</View >
		)
	}
}
